<?php
    //this file contains the entry point of the fetion client
    //manage fetion to send message to implement the service
    //this connector based on a local running python fetion client
    //the python fetion client based on the cocobear library and implement
    //as the project's back process

    //using fetion api to send message
    if (!defined('MSG_CONNECTOR_FETION_USERNAME') ||
        !defined('MSG_CONNECTOR_FETION_PASSWORD')){
            report_notice('Please define connector options!');
        }
    define('FETION_API_URL', 'https://fetionapi.appspot.com/api/?%s');
    
    function accessUrl($url){
        $cl = curl_init($url);
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($cl, CURLOPT_RETURNTRANSFER, true);
        $info = curl_exec($cl);
        return $info;
    }
    
    function addBuddy($add){
        accessUrl(sprintf(FETION_API_URL, http_build_query(
                array(
                    'from' => MSG_CONNECTOR_FETION_USERNAME,
                    'pw' => MSG_CONNECTOR_FETION_PASSWORD,
                    'add' => $add
                ))));
    }
    
    function sendMsg($to, $msg){
        $info = accessUrl(sprintf(FETION_API_URL, http_build_query(
                array(
                    'from' => MSG_CONNECTOR_FETION_USERNAME,
                    'pw' => MSG_CONNECTOR_FETION_PASSWORD,
                    'to' => $to,
                    'msg' => $msg
                )))
        );
        $regex = '/' . preg_quote('成功') . '/';
        if (!preg_match($regex, $info)){
            //not success
            //add buddy and try
            addBuddy($to);
            $info = accessUrl(sprintf(FETION_API_URL, http_build_query(
                array(
                    'from' => MSG_CONNECTOR_FETION_USERNAME,
                    'pw' => MSG_CONNECTOR_FETION_PASSWORD,
                    'to' => $to,
                    'msg' => $msg
                )))
            );
            if (!preg_match($regex, $info)){
                return false;
            }
            else{
                return true;
            }
        }
        else{
            return true;
        }
    }
    
    function getMsg(){
        throw new Exception('not implemented');
    }